# -*- coding: utf-8 -*-
'''
    :file: static.py
    :author: -Farmer
    :url: https://blog.farmer233.top
    :date: 2021/04/27 19:55:45
'''
import os
from core.utils.http import HttpRequest, HttpResponse
from core.config import BASE_DIR, INDEX_FILE, STATIC_FOLDER

def static(request:HttpRequest):
    """静态资源控制器"""
    MIME_TYPE = {
        'css': 'text/css; charset=UTF-8',
        'js': 'application/javascript; charset=UTF-8',
        'png': 'image/png',  # 文件需要返回二进制
        'jpg': 'image/jpeg',
        'ico': 'image/x-icon',
        'woff': 'application/font-woff2',
        'mp4': 'video/mp4',
        '/': 'text/html; charset=utf-8'
    }

    # 请求路径格式：/static/css/style.css
    # 根据请求路径中的文件名后缀判断静态文件类型，指定响应首部字段 Content-Type
    file_type = request.path.split('.')[-1]
    if file_type.startswith('woff'):
        file_type = 'woff'
    if file_type.startswith('woff2'):
        file_type = 'woff2'
    
    headers = {
        'Content-Type': MIME_TYPE.get(file_type, None),
    }

    # 获取静态资源绝对路径
    print('[INFO]', request.method, request.path)
    path = request.path.split('/')
    if path[-1]=='':
        path[-1] = f'{INDEX_FILE}'
    path = os.sep.join(path[1:])
    file_path = os.path.join(STATIC_FOLDER, path)

    if 'htm' in file_type or 'css' in file_type or 'js' in file_type:
        with open(file_path, 'r', encoding='utf-8') as f:
            body = f.read()
    else:
        with open(file_path, 'rb') as f:
            body = f.read()


    return HttpResponse(body=body, headers=headers)